class DeclarationsController < ApplicationController

  before_filter :access, :except => [:index, :show, :new, :create, :my]
  
  cache_sweeper :balance_sweeper
  
  sidebar :deposits, :if => :logged_in?
  sidebar :ajax_module_balans, :if => :logged_in?

  #Actions: list, new, edit, create, update, delete
  
  def index
    list
    render :action => 'list'
  end

  def list
    #@declaration_pages, @declarations = paginate :declaration, :per_page => 10, :order => 'created_at desc'
    @declarations = Declaration.paginate :page => params[:page]
  end

  def show
    @declaration = Declaration.find(params[:id])
  end

  def new
    @declaration = Declaration.new
    @declaration.owner = current_user
    
  end
  
  def create
    @declaration = Declaration.new(params[:declaration])
    
    @declaration.owner = current_user
    
    if @declaration.save
      flash[:message] = 'Declaratie opgeslagen!'
      return(redirect_to :controller => 'dashboard')
    end
    
    render :action => 'new'
    
  end

  def update
    #Must be find_by_id and not find()
    @declaration.attributes = params[:declaration]
    
    if @declaration.save
      flash[:message] = 'De declaratie is opgeslagen.'
    else
      flash[:error] = 'Er ging iets mis bij het opslaan van de declaratie!'
      return (render :action => 'edit')
    end
    
    redirect_to :controller => 'dashboard'
  end

  def edit
    #@edit wordt opgehaald in .access
  end

  def destroy
    Declaration.find(params[:id]).destroy
    redirect_to :action => 'list'
  end
  
  def my
    @search = params[:search]
    
    @my_declarations = current_user.declarations.find_by_description_like( :all, @search )
  end

  private
  def access
    #Only the last 5 declarations can be edited
    @editable_declarations = Declaration.find(:all, :limit => 5, :order => "created_at DESC")
    
    #Check if the declaration is in the editable list
    @declaration = @editable_declarations.select {|d| d.id == params[:id].to_i }[0]
    
    if not @declaration
      flash[:error] = 'Je hebt geen rechten om deze declaratie te bewerken. Je bent toch niet aan het hacken?'
      begin
        redirect_to :back
      rescue
        redirect_to :controller => 'dashboard'
      end
    end
  end
  
end